// This was added by Jason MacDuffie in 2014

import java.io.*;
import java.nio.charset.*;
import java.nio.file.*;
import java.net.URL;
import java.awt.*;
import java.awt.image.BufferedImage;
import javax.imageio.*;
import javax.swing.*;

public class HtmlReader {
  public static String readLocalFile(String filepath) {
    URL dirpath = HtmlReader.class.getProtectionDomain().getCodeSource().getLocation();
    String localPath = dirpath.toString().replace("file:", "").replace("%20", " ").replace("CipherBuddy.jar", "") + filepath;
    String content = null;
    try {
        content = readFile(localPath, Charset.defaultCharset());
    } catch (IOException e) { System.err.println(e); }
    return "<html><body style='width: 200 px'" + content + "</html>";
  }

  public static Image readLocalImage(String filepath) {
    URL dirpath = HtmlReader.class.getProtectionDomain().getCodeSource().getLocation();
    String localpath = dirpath.toString().replace("file:", "").replace("%20", " ").replace("CipherBuddy.jar", "") + filepath;
    BufferedImage bitmap = null;
    ByteArrayOutputStream bytes = new ByteArrayOutputStream();
    try {
      bitmap = ImageIO.read(new File(localpath));
      ImageIO.write(bitmap, "PNG", bytes);
    } catch (IOException e) { System.err.println(e); }
    return (new ImageIcon(bytes.toByteArray())).getImage();
  }

  public static String readFile(String path, Charset encoding) throws IOException {
    byte[] encoded = Files.readAllBytes(Paths.get(path));
    return new String(encoded, encoding);
  }
}
